package com.mall4j.cloud.gateway;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoggingFilter implements GlobalFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 记录请求信息
        logger.info("Request: {} {}", exchange.getRequest().getMethod(), exchange.getRequest().getURI());

        // 记录请求头
        exchange.getRequest().getHeaders().forEach((name, values) ->
                values.forEach(value -> logger.info("Request Header: {}={}", name, value)));

        // 记录响应信息
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            logger.info("Response Status: {}", exchange.getResponse().getStatusCode());

            // 如果需要记录响应体，需要缓存响应体
            // 注意：这会增加内存消耗
            exchange.getResponse().getHeaders().forEach((name, values) ->
                    values.forEach(value -> logger.info("Response Header: {}={}", name, value)));
        }));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}